<?php

/**
 * 应用API
 * 
 * @author ShuangYa
 * @package EUser
 * @category Controller
 * @link http://www.sylingd.com/
 * @copyright Copyright (c) 2015 ShuangYa
 * @license http://lab.sylingd.com/go.php?name=euser&type=license
 */

namespace euser\controller;
use \Sy;
use \sy\base\Controller;
use \sy\lib\YHtml;
use \sy\lib\YCookie;
use \sy\lib\YSecurity;
use \euser\libs\Common;

class App extends Controller {
	public function __construct() {
		$this->a = Sy::service('app');
	}
	protected function parseSdkData($requestId) {
		if (Sy::$httpRequest[$requestId]->header['x-method'] === 'SDK-HTTP') {
			//SDK方式请求
			$data = Sy::$httpRequest[$requestId]->rawContent();
			Sy::$httpRequest[$requestId]->post = json_decode($data, 1);
			$app = $this->a->getClient(Sy::$httpRequest[$requestId]->post['client_id']);
			$sign = $this->a->createSign($data, $app['secret']);
			if ($sign !== Sy::$httpRequest[$requestId]->header['x-sign']) {
				Sy::setMimeType('json', $requestId);
				Sy::$httpResponse[$requestId]->write(Common::getAjax(['error' => 'invalid_sign']));
				return FALSE;
			}
			return TRUE;
		}
	}
	//[API]获取应用信息
	public function actionGet($requestId = NULL, $apiData = FALSE) {
		if (!$apiData) {
			if (Sy::$httpRequest[$requestId]->header['x-method'] !== 'SDK-HTTP') {
				return;
			}
			if (!$this->parseSdkData($requestId)) {
				return;
			}
			Sy::setMimeType('json', $requestId);
			$id = Sy::$httpRequest[$requestId]->post['id'];
			$client_id = Sy::$httpRequest[$requestId]->post['client_id'];
		} else {
			$id = $apiData['id'];
			$client_id = $apiData['client_id'];
		}
		$c = $this->a->getClient($id);
		$c['_id'] = strval($c['_id']);
		$app = $this->a->getClient($client_id);
		if (!is_array($app['scope']) || !in_array('app_get_secret', $app['scope'], TRUE)) {
			unset($c['secret']);
		}
		if ($apiData) {
			return $c;
		} else {
			Sy::$httpResponse[$requestId]->write(Common::getAjax($c));
		}
	}
}
